layui.define(
    ["layer", "globalConfig", "laytpl", "sdLocal", "sdDialog"],
    function(exports) {
        let $ = layui.jquery;
        let layer = layui.layer;
        let sdLocal = layui.sdLocal;
		let sdDialog =layui.sdDialog;
        let globalConfig = layui.globalConfig;
        let body = ".layui-layout-admin>.layui-body";
        let tab = body + ">.layui-tab";
        let j = false;
        
   
        let sysApplication = {
            auth: function(){
                let url = window.location.href;

                let item = url.split('#');
                let route = '#' + item[1];

                let auth = [];
                $.each(sdLocal.menus.get(), function (i, item) {
                    if (item.url == route) {
                        auth = item.permission;
                    }
                })
                // 排序
                auth.sort((a, b) => {
                    return b['sortId'] - a['sortId']
                })
                return auth;
            },
            btns: {
                top: function () {
                    return sysApplication.permission(1);
                },
                right: function () {
                    return sysApplication.permission(2);
                }
            },
            permission: function (type) {
                let top = "", right = "";
                $.each(sysApplication.auth(), function (i, o) {
                    if(o.type == 1){
                        let color = (o.event).indexOf("delete") >=0 ? "layui-btn-danger" : "";
                        right += "<a data-flag=\"" + o.flag + "\" class=\"layui-btn " + color + " layui-btn-xs\" lay-event=\"" + o.event + "\">" + o.name + "</a>";
                    }
                    if(o.type == 2){
                        top += "<button data-flag=\"" + o.flag + "\" class=\"layui-btn layui-btn-sm\" lay-event=\"" + o.event + "\">" + o.name + "</button>";
                    }
                })
                return "<div>" + (type == 1 ? top : right) + "</div>";
            },
            closeThisTabs: function(page) {
                sysApplication.closeTabOperNav();
                let title = $(tab + ">.layui-tab-title");
                if (!page) {
                    if (title.find("li").first().hasClass("layui-this")) {
                        layer.msg("主页不能关闭", {
                            icon: 2
                        });
                        return
                    }
                    title.find("li.layui-this").find(".layui-tab-close").trigger("click")
                } else {
                    if (page == title.find("li").first().attr("lay-id")) {
                        layer.msg("主页不能关闭", {
                            icon: 2
                        });
                        return
                    }
                    title.find('li[lay-id="' + p + '"]').find(".layui-tab-close").trigger("click")
                }
            },
            closeOtherTabs: function(page) {
                if (!page) {
                    $(tab + ">.layui-tab-title li:gt(0):not(.layui-this)").find(".layui-tab-close").trigger("click")
                } else {
                    $(tab + ">.layui-tab-title li:gt(0)").each(function() {
                        if (page != $(this).attr("lay-id")) {
                            $(this).find(".layui-tab-close").trigger("click")
                        }
                    })
                }
                sysApplication.closeTabOperNav()
            },
            closeAllTabs: function() {
                $(tab + ">.layui-tab-title li:gt(0)").find(".layui-tab-close").trigger("click");
                $(tab + ">.layui-tab-title li:eq(0)").trigger("click");
                sysApplication.closeTabOperNav()
            },
            closeTabOperNav: function() {
                $(".layui-icon-down .layui-nav .layui-nav-child").removeClass("layui-show")
            },
        };

        layui.use(['sysViews', 'sdDialog', 'sdEncrypt'], function () {
            let sysViews = layui.sysViews;
            let sdDialog = layui.sdDialog;
            let sdEncrypt = layui.sdEncrypt;

            sysApplication.events = {
                closeThisTabs: function() {
                    sysApplication.closeThisTabs()
                },
                closeOtherTabs: function() {
                    sysApplication.closeOtherTabs()
                },
                closeAllTabs: function() {
                    sysApplication.closeAllTabs()
                },
                switchApp: function () {
                    let obj = $(this);
                    let check = obj.attr('data-check');
                    if(check == 0){
                        layer.confirm("确定要切换到当前选择的子系统？", {
                            title: "温馨提示",
                            skin: "layui-layer-admin"
                        }, function(index) {
                            $('.application-item').attr('data-check', 0);
                            $('.application-item').removeClass('green');
                            $('.application-item').addClass('orangered');
                            $('.application-item').find('span').html('前往');
                            $('.application-item').find('i').removeClass('layui-icon-home');
                            $('.application-item').find('i').addClass('layui-icon-release');

                            obj.attr('data-check', 1);
                            obj.removeClass('orangered');
                            obj.addClass('green');
                            obj.find('span').html('使用中');

                            obj.find('i').removeClass('layui-icon-release');
                            obj.find('i').addClass('layui-icon-home');
                            // 设置子系统缓存
                            let app = {
                                id: obj.attr('data-id'),
                                name: obj.attr('data-name'),
                                panel: obj.attr('data-panel')
                            }
                            
                            sdLocal.app.put(app);
                            layer.close(index);
                            location.replace('/cut_application.html');
                        })
                    }
                },
                flexible: function() {
                    let p = $(".layui-layout-admin").hasClass("admin-nav-mini");
                    sysViews.flexible(p)
                },
                refresh: function() {
                    sysViews.refresh()
                },
                back: function() {
                    history.back()
                },
                theme: function() {
                    sdDialog.rightView("theme");
                },
                note: function() {
                    sdDialog.rightView("note");
                },
                config: function(){
                    sdDialog.rightView("config");
                },
                message: function() {
                    sdDialog.rightView("message");
                },
                application: function() {
                    sdDialog.rightView("application");
                },
                psw: function() {
                    sdDialog.popupCenter({
                        height: '320px',
                        width: '320px',
                        title: "修改密码",
                        path: "/components/common/password.html",
                        opt: function (index) {
                            let oldPwd = $('#oldPwd').val();
                            let newPwd = $('#newPwd').val();
                            let rePwd = $('#rePwd').val();
                            if($.trim(oldPwd).length < 5 || $.trim(oldPwd).length > 16){
                                layx.notice({
                                    title: '温馨提示',
                                    message: '旧密码字符长度为6-16个字符'
                                });
                                return false;
                            }
                            if($.trim(newPwd).length < 5 || $.trim(newPwd).length > 16){
                                layx.notice({
                                    title: '温馨提示',
                                    message: '新密码字符长度为6-16个字符'
                                });
                                return false;
                            }
                            if($.trim(rePwd).length < 5 || $.trim(rePwd).length > 16){
                                layx.notice({
                                    title: '温馨提示',
                                    message: '确认密码字符长度为6-16个字符'
                                });
                                return false;
                            }
                            if($.trim(rePwd) != $.trim(newPwd)){
                                layx.notice({
                                    title: '温馨提示',
                                    message: '新密码和确认密码不一至'
                                });
                                return false;
                            }
                            let data = {
                                oldPwd: sdEncrypt.sha1(oldPwd),
                                newPwd: sdEncrypt.sha1(newPwd)
                            }
                            let header = {
                                "Content-Type": "application/json;charset=UTF-8",
                                "token": (typeof sdLocal.token.get()) == 'undefined' ? '' : sdLocal.token.get()
                            };
                            $.ajax({
                                type: "POST",
                                url: globalConfig.action + '/v1/platform/iam/password',
                                data: JSON.stringify(data),
                                contentType: "application/json;charset=UTF-8",
                                local: false,
                                headers: header,
                                dataType: 'json',
                                error: function (e) {
                                    let res = e.responseJSON;
                                    layx.notice({
                                        title: '温馨提示',
                                        message: res.msg
                                    });
                                },
                                success: function(d){
                                    layx.notice({
                                        title: '成功提示',
                                        type: 'success',
                                        message: d.msg
                                    });
                                    setTimeout(function () {
                                        sdLocal.clean();
                                        location.replace('/login.html');
                                    }, 3000)
                                }
                            });
                        }
                    })
                },
                logout: function() {
                    layer.confirm("确定要退出登录吗？", {
                        title: "温馨提示",
                        skin: "layui-layer-admin"
                    }, function() {
                        sdLocal.clean();
                        location.replace('/login.html');
                    })
                },
                fullScreen: function(v) {
                    let full = "layui-icon-screen-full",
                        restore = "layui-icon-screen-restore";
                    let icon = $(this).find("i");
                    let el = document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || false;
                    if (el) {
                        let exit = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
                        if (exit) {
                            exit.call(document)
                        } else {
                            if (window.ActiveXObject) {
                                let shell = new ActiveXObject("WScript.Shell");
                                shell && shell.SendKeys("{F11}")
                            }
                        }
                        icon.addClass(full).removeClass(restore)
                    } else {
                        let el = document.documentElement;
                        let open = el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen || q.msRequestFullscreen;
                        if (open) {
                            open.call(el)
                        } else {
                            if (window.ActiveXObject) {
                                let shell = new ActiveXObject("WScript.Shell");
                                shell && shell.SendKeys("{F11}")
                            }
                        }
                        icon.addClass(restore).removeClass(full)
                    }
                }
            };
            $(document).on("click", "*[click-event]", function() {
                let event = $(this).attr("click-event");
				
                let events = sysApplication.events[event];
                events && events.call(this, $(this))
            });

            $(document).on("mouseenter", "*[lay-tips]", function() {
                let tips = $(this).attr("lay-tips");
                let direction = $(this).attr("lay-direction");
                let bg = $(this).attr("lay-bg");
                layer.tips(tips, this, {
                    tips: [direction || 3, bg || "#333333"],
                    time: -1
                })
            }).on("mouseleave", "*[lay-tips]", function() {
                layer.closeAll("tips")
            });

            $(document).on("mouseenter", ".layui-layout-admin.admin-nav-mini .layui-side .layui-nav .layui-nav-item>a", function() {
                if (sysViews.getPageWidth() > 750) {
                    let r = $(this);
                    $(".admin-nav-hover>.layui-nav-child").css("top", "auto");
                    $(".admin-nav-hover").removeClass("admin-nav-hover");
                    r.parent().addClass("admin-nav-hover");
                    let p = $(".admin-nav-hover>.layui-nav-child");
                    if (p.length > 0) {
                        sysViews.setNavHoverCss(r)
                    } else {
                        let q = r.find("cite").text();
                        layer.tips(q, r, {
                            tips: [2, "#333333"],
                            time: -1
                        })
                    }
                }
            }).on("mouseleave", ".layui-layout-admin.admin-nav-mini .layui-side .layui-nav .layui-nav-item>a", function() {
                layer.closeAll("tips")
            });

            $(document).on("mouseleave", ".layui-layout-admin.admin-nav-mini .layui-side", function() {
                j = false;
                setTimeout(function() {
                    if (!j) {
                        sysViews.removeNavHover()
                    }
                }, 500)
            });

            $(document).on("mouseenter", ".layui-layout-admin.admin-nav-mini .layui-side .layui-nav .layui-nav-item.admin-nav-hover .layui-nav-child", function() {
                j = true
            });

            exports('sysApplication', sysApplication)
        })

    }
)